package vn.axonactive.devday.jsf.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import vn.axonactive.devday.jsf.model.stockfeed.StockQuoteFactory;

@ManagedBean
@ApplicationScoped
public class StocksModel {
	
	private List<StockQuote> stocks;

	@PostConstruct
	public void init() {
		try {
			stocks = StockQuoteFactory.getInstance().feedData();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public List<StockQuote> getStocks() {
		return stocks;
	}

	/**
	 * Returns a list of stocks which contains the given search string in their symbol name (case insensitive)
	 */
	public List<StockQuote> findStocksBySymbol(String searchString) {
		List<StockQuote> filteredStocks = new ArrayList<StockQuote>();
		if (searchString == null) {
			searchString = "";
		}
		searchString = searchString.toLowerCase();
		
		for (StockQuote stockQuote : stocks) {
			String symbol = stockQuote.getSymbol().toLowerCase();
			if (symbol.contains(searchString)) {
				filteredStocks.add(stockQuote);
			}
		}
		
		return filteredStocks;
	}
	
}
